package algorithm;

import java.util.Arrays;

/**
 * @Description: 冒泡排序
 * @Author: hmm
 * @CreateDate: 2019/8/26
 * @UpdateUser:
 * @UpdateDate: 2019/8/26
 * @UpdateRemark: 修改备注
 * @Version: 1.0
 */
public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {5, 58, 12, 4, 3, 45, 32, 11, 25, 235, 32, 22};

        for (int i = 0; i < arr.length; i++) {
            //此标志针对数组本来就是从小到大排列好的 循环一次后确定 就中止执行
            boolean isSwap = false;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j+1);
                    isSwap = true;
                }
            }
            if (!isSwap) {
                break;
            }
        }
        System.out.println(Arrays.toString(arr));
    }

    private static void swap(int[] arr, int i, int j) {
        //异或运算  相同为0   0^N = N    N^N = 0
        //假设 arr[i] = 甲  arr[j] = 乙
        //1. arr[i] = 甲^乙   arr[j] = 乙
        arr[i] = arr[i] ^ arr[j];
        //2. arr[i] = 甲^乙   arr[j] = 甲^乙^乙 = 甲^(乙^乙) = 甲
        arr[j] = arr[i] ^ arr[j];
        //3. arr[i] = 甲^乙^甲 = (甲^甲)^乙 = 乙
        arr[i] = arr[i] ^ arr[j];
//        int temp = arr[j];
//        arr[j] = arr[j + 1];
//        arr[j + 1] = temp;
    }
}
